package com.yuns.web.auth.controller;

import com.alibaba.fastjson.JSONObject;
import com.yuns.common.utils.*;
import com.yuns.web.auth.api.AuthApi;
import com.yuns.web.auth.api.companyInfoBaseApi;
import com.yuns.web.auth.param.CompanyUserRegParam;
import com.yuns.web.auth.param.WechatUser;
import com.yuns.web.course.api.CompanyUserBaseApi;
import com.yuns.web.course.param.CompanyUserBase;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@RestController
@Slf4j
@Api(tags = "登录注册相关 - Controller")
public class AuthController {

    @Autowired
    private AuthApi authApi;

    @Autowired
    private com.yuns.web.auth.api.companyInfoBaseApi companyInfoBaseApi;

    @Autowired
    private CompanyUserBaseApi companyUserBaseApi;

    @Autowired
    private StringRedisTemplate redisTemplate;

    private String wxAppid = "wx475418041d61daa3";

    private String wxSecret = "4f1e31cf4b9dd4d9a8199b5c9ce1c688";

    /**
     * 企业列表下拉框查询
     *
     * @return
     */
    @ApiOperation(value = "企业列表下拉框查询")
    @PostMapping("queryComsList")
    public ResultJson queryComsList() {
        return companyInfoBaseApi.queryList();
    }


    /**
     * 账号密码登录
     *
     * @return
     */
    @ApiOperation(value = "账号密码登录授权")
    @PostMapping("accountLogin")
    public ResponseEntity<ResultJson> accountLogin(@RequestBody SysUser userDto,
                                                   HttpServletRequest request,
                                                   HttpServletResponse response) {
        // 登录校验
        ResultJson resultJson = authApi.accountLogin(userDto.getUserName(), userDto.getPassword());
        if (resultJson.getCode() == 900) {
            return ResponseEntity.ok(resultJson);
        }
        // 如果有查询结果，则生成token
        String token = TokenUtils.token(userDto.getUserName(), userDto.getPassword());
        // 将token写入cookie,并指定httpOnly为true，防止通过JS获取和修改
        CookieUtils.setCookie(request, response, "token", token, 1200, true);
        //把token返回，防止塞cookie不成功
        resultJson.setMsg(token);
        return ResponseEntity.ok(resultJson);
    }

    /**
     * 手机号登录
     *
     * @return
     */
    @ApiOperation(value = "手机号登录")
    @PostMapping("telLogin")
    public ResponseEntity<ResultJson> telLogin(@RequestBody SysUser userDto,
                                               HttpServletRequest request,
                                               HttpServletResponse response
    ) {
        // 登录校验
        ResultJson resultJson = authApi.telLogin(userDto.getPhone(), userDto.getCode());
        if (resultJson.getCode() == 900) {
            return ResponseEntity.ok(resultJson);
        }
        // 如果有查询结果，则生成token
        String token = TokenUtils.token_phone(userDto.getPhone(), userDto.getCode());
        // 将token写入cookie,并指定httpOnly为true，防止通过JS获取和修改
        CookieUtils.setCookie(request, response, "token", token, 1200, true);
        //把token返回，防止塞cookie不成功
        resultJson.setMsg(token);
        return ResponseEntity.ok(resultJson);
    }

    /**
     * 验证用户登录状态
     *
     * @param token
     * @return
     */
    @ApiOperation(value = "验证用户登录状态")
    @GetMapping("verify")
    public ResponseEntity<Void> verifyUser(@RequestParam("token") String token, HttpServletRequest request, HttpServletResponse response) {
        try {
            //判断token是否有效
            boolean cache = TokenUtils.verify(token);
            if (!cache) {
                // 更新cookie中的token
                CookieUtils.setCookie(request, response, "token", null, 1200, true);
                // 解析成功返回用户信息
                return new ResponseEntity<>(HttpStatus.UNAUTHORIZED);
            }
            return ResponseEntity.ok().build();
        } catch (Exception e) {
            return ResponseEntity.badRequest().build();
        }
    }

    /**
     * 发送短信
     *
     * @param phone
     * @return
     */
    @ApiOperation(value = "发送短信")
    @GetMapping("code")
    public ResultJson sendCode(@RequestParam("phone") String phone) {
        return authApi.sendCode(phone);
    }

    /**
     * 手机号注册
     *
     * @return
     */
    @ApiOperation(value = "手机号注册")
    @PostMapping("registerByTel")
    public Object registerByTel(@RequestBody SysUser userDto) {
        return authApi.registerByTel(userDto);
    }

    /**
     * 企业员工注册
     *
     * @param companyUserRegParam
     * @return
     */
    @ApiOperation(value = "企业员工注册")
    @PostMapping("register")
    public Object register(@RequestBody CompanyUserRegParam companyUserRegParam) {
        return authApi.register(companyUserRegParam);
    }

    /**
     * 退出操作
     *
     * @param request
     * @param response
     * @return
     * @Param token
     */
    @ApiOperation(value = "退出操作")
    @PostMapping("logout")
    public ResultJson logout(@RequestParam("token") String token, HttpServletRequest request, HttpServletResponse response) {
        try {
            CookieUtils.setCookie(request, response, "token", null, 1200, true);
            return ResultJson.ok();
        } catch (Exception e) {
            return ResultJson.error();
        }
    }

    /**
     * 微信授权
     *
     * @param code
     * @return
     */
    @ApiOperation(value = "微信授权 - getOpenId")
    @PostMapping(value = "getOpenId")
    public ResultJson getOpenId(@RequestParam("code") String code) {
        String getopenid_url = "https://api.weixin.qq.com/sns/oauth2/access_token";
        String param =
                "appid=" + wxAppid + "&secret=" + wxSecret + "&code=" + code + "&grant_type=authorization_code";
        //向微信服务器发送get请求获取openIdStr
        String openIdStr = HttpRequest.sendGet(getopenid_url, param);
        JSONObject json = JSONObject.parseObject(openIdStr);//转成Json格式
        String openId = json.getString("openid");//获取openId
        String nickname=json.getString("nickname");
        String headimgurl=json.getString("headimgurl");
        WechatUser wechatUser=new WechatUser();
        wechatUser.setOpenid(openId);
        wechatUser.setNickname(nickname);
        wechatUser.setHeadimgurl(headimgurl);

        BasePage<CompanyUserBase> frontPage =new BasePage<CompanyUserBase>();
        CompanyUserBase companyUserBase=new CompanyUserBase();
        companyUserBase.setUserName(nickname);
        frontPage.setData(companyUserBase);
        ResultJson resultJson=companyUserBaseApi.query(frontPage);
        if(resultJson!=null && resultJson.getData()!=null && json!=null && nickname!=null){
            wechatUser.setFlag(true);
            wechatUser.setCompanyUserBase(resultJson.getData());
        }else {
            wechatUser.setFlag(false);
        }
        return ResultJson.ok(wechatUser);
    }


}